package com.xiaomazi.acl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaomazi.acl.entity.Permission;
import com.xiaomazi.acl.entity.RolePermission;
import com.xiaomazi.acl.entity.User;
import com.xiaomazi.acl.mapper.PermissionMapper;
import com.xiaomazi.acl.service.PermissionService;
import com.xiaomazi.acl.service.RolePermissionService;
import com.xiaomazi.acl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: llxy-parent
 * @description: 权限业务类
 * @author: 小马子
 * @create: 2023-03-14 13:27
 **/
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {


    @Autowired
    private UserService userService;

    @Autowired
    private RolePermissionService rolePermissionService;


    /**
     * 查询出所有权限，并构建成树形结构
     * @return permissionList
     */
    @Override
    public List<Permission> queryAllMenu() {
        return build(this.query().orderByAsc("type").list());
    }



    /**
     * 根据id递归删除权限
     * @param id 权限id
     */
    @Override
    public void removeChildById(String id) {
        List<String> childrenIds = new ArrayList<>();
        selectChildrenIdsByParentId(id,childrenIds);
        childrenIds.add(id);

        this.removeBatchByIds(childrenIds);
    }




    /**
     * 给角色分配权限
     * @param roleId       角色id
     * @param permissionIds 权限ids
     */
    @Override
    public void saveRolePermissionRealtionShip(String roleId, String[] permissionIds) {
        rolePermissionService.update().eq("role_id",roleId).remove();


        List<RolePermission> rolePermissionList = new ArrayList<>();
        for (String permissionId : permissionIds) {
            if (StrUtil.isBlank(permissionId)) continue;
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionList.add(rolePermission);
        }

        rolePermissionService.saveBatch(rolePermissionList);
    }





    /*--------------------------------------------------工具方法------------------------------------------------------*/
    /**
     * 根据用户id查询用户对应的所有权限列表
     * @param id 用户id
     * @return List
     */
    @Override
    public List<String> selectPermissionValueByUserId(String id) {
        return isSysAdmin(id) ?
                baseMapper.selectAllPermissionValue()
                :
                baseMapper.selectPermissionValueByUserId(id);
    }

    /**
     * 根据角色获取菜单
     * @param roleId 角色Id
     * @return List<Permission>
     */
    @Override
    public List<Permission> selectAllMenu(String roleId) {
        List<RolePermission> rolePermissionList = rolePermissionService.query().eq("role_id", roleId).select("permission_id").list();
        List<String> PermissionIds = rolePermissionList.stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
        List<Permission> permissions = this.query().in("id", PermissionIds).list();
        permissions.stream().forEach(item -> item.setSelect(true));
        return build(permissions);
    }

    /**
     * 判断用户是否系统管理员
     * @param userId
     * @return
     */
    private boolean isSysAdmin(String userId) {
        User user = userService.getById(userId);

        if(null != user && "admin".equals(user.getUsername())) {
            return true;
        }
        return false;
    }

    private List<Permission> build(List<Permission> permissionList) {
        List<Permission> treeList = new ArrayList<>();
        permissionList.stream().forEach(permission -> {
            if (0 == permission.getType()) {
                permission.setLevel(1);
                treeList.add(buildTree(permission,permissionList));
            }
        });
        return treeList;
    }


    /**
     * 递归构建树形结构
     * @param treeNode 节点
     * @param permissionList 集合
     * @return Permission
     */
    private Permission buildTree(Permission treeNode, List<Permission> permissionList) {
        treeNode.setChildren(new ArrayList<Permission>());

        permissionList.stream().forEach(node -> {
            if (node.getPid().equals(treeNode.getId())) {
                node.setLevel(treeNode.getLevel() + 1);
                treeNode.getChildren().add(buildTree(node,permissionList));
            }
        });
        return treeNode;
    }


    /**
     * 递归查询该id下所有孩子节点id
     * @param id 父id
     * @param childrenIds 所有孩子节点id集合
     */
    private void selectChildrenIdsByParentId(String id, List<String> childrenIds) {
        List<Permission> permissionList = this.query().eq("pid", id).select("id").list();
        if (null != permissionList && !permissionList.isEmpty()){
            List<String> ids = permissionList.stream().map(Permission::getId).collect(Collectors.toList());
            ids.stream().forEach(itemId -> {
                childrenIds.add(itemId);
                selectChildrenIdsByParentId(itemId,childrenIds);
            });
        }
    }
}
